import 'package:animation/api/video.dart';
import 'package:animation/components/AlertDialog/my_loading.dart';
import 'package:animation/components/avatar.dart';
import 'package:animation/components/empty.dart';
import 'package:animation/generated/l10n.dart';
import 'package:animation/pages/other/navchild/update_list.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';

import '../other/navchild/search_page.dart';

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage>
    with TickerProviderStateMixin, AutomaticKeepAliveClientMixin {
  List updateListInfo = [];
  late TabController tabController;
  int activeIndex = 0;
  PageController pageController = PageController(initialPage: 0);
  List<Widget> subList = [];
  bool isLoading = false;

  void getUpdateList() async {
    setState(() {
      isLoading = true;
    });
    List weeks = ['一', '二', '三', '四', '五', '六', '日'];
    DateTime now = DateTime.now();
    String date = '${now.month}-${now.day}';
    if (!mounted) return;
    try {
      Response res = await updateList();
      List list = res.data['result'];
      setState(() {
        for (var i = 0; i < list.length; i++) {
          updateListInfo.add(list[i]);
          if (list[i]['date'] == date) {
            activeIndex = i;
          }
        }
        tabController = TabController(
            length: list.length, vsync: this, initialIndex: activeIndex);
        for (var i = 0; i < list.length; i++) {
          subList.add(Tab(
            child: Column(
              children: [
                Text(list[i]['date'] == date
                    ? '今'
                    : weeks[list[i]['day_of_week'] - 1]),
                Text(list[i]['date']),
              ],
            ),
          ));
        }
      });

      // 延迟跳转到指定页面
      WidgetsBinding.instance.addPostFrameCallback((_) {
        if (mounted && pageController.hasClients) {
          pageController.jumpToPage(activeIndex);
        }
      });
    } catch (e) {
      print(e);
    } finally {
      setState(() {
        isLoading = false;
      });
    }
  }

  @override
  void initState() {
    super.initState();
    getUpdateList();
    tabController = TabController(length: 0, vsync: this);
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      appBar: AppBar(
        toolbarHeight: 40,
        elevation: 0,
        backgroundColor: Theme.of(context).colorScheme.primaryContainer,
        surfaceTintColor: Theme.of(context).colorScheme.primaryContainer,
        title: _buildHeader(context),
      ),
      body: Column(
        children: [
          if (subList.isNotEmpty)
            Container(
              color: Theme.of(context).colorScheme.primaryContainer,
              child: TabBar(
                tabs: subList,
                dividerColor: Colors.transparent,
                labelColor: Theme.of(context).colorScheme.primary,
                unselectedLabelColor: Theme.of(context).colorScheme.onSurface,
                controller: tabController,
                isScrollable: true,
                tabAlignment: TabAlignment.start, // 元素对齐方式
                indicatorPadding: const EdgeInsets.all(0), // 调整指示器的内边距
                indicatorSize: TabBarIndicatorSize.label, // 使用标签的宽度
                indicator: BoxDecoration(),
                onTap: (index) {
                  pageController.jumpToPage(index);
                },
              ),
            ),
          if (subList.isNotEmpty)
            Expanded(
                child: PageView.builder(
                    itemCount: updateListInfo.length,
                    controller: pageController,
                    onPageChanged: (index) {
                      tabController.animateTo(index);
                    },
                    itemBuilder: (context, index) {
                      return UpdateList(
                        updateListInfo: updateListInfo[index]['seasons'],
                      );
                    })),
          if (subList.isEmpty && isLoading == false) Empty(),
          if (isLoading)
            Expanded(
              child: MyLoading(
                size: 60,
              ),
            ),
        ],
      ),
    );
  }

  Widget _buildHeader(BuildContext context) => Container(
        color: Theme.of(context).colorScheme.primaryContainer,
        child: Row(children: [
          Avatar(),
          Expanded(
            child: InkWell(
              onTap: () {
                Navigator.push(context,
                    MaterialPageRoute(builder: (context) => SearchPage()));
              },
              child: Container(
                margin: const EdgeInsets.only(left: 10, right: 10),
                height: 28,
                decoration: BoxDecoration(
                    color: Theme.of(context).colorScheme.surface,
                    borderRadius: const BorderRadius.all(Radius.circular(15))),
                child: Flex(direction: Axis.horizontal, children: [
                  const SizedBox(width: 10),
                  const Icon(Icons.search, color: Colors.grey),
                  Text(S.of(context).a2,
                      style: TextStyle(fontSize: 14, color: Colors.grey)),
                ]),
              ),
            ),
          ),
          InkWell(
            onTap: () {},
            child: Icon(
              Icons.favorite_sharp,
              color: Theme.of(context).colorScheme.onSurface,
              size: 26,
            ),
          ),
        ]),
      );

  @override
  bool get wantKeepAlive => true;
}
